﻿// Matt's TinyMVC Copyright (c) 2009 Matt J. Crouch

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace MattsTinyMVC
{
    [Serializable]
    public abstract class BaseController : BaseModel
    {
        protected BaseController()
            : base()
        {
            _modelLocator = new Dictionary<int, BaseModel>();
        }

        [NonSerialized]
        private object _controllerState;
        public object ControllerState
        {
            get { return _controllerState; }
            set { _controllerState = value; }
        }

        [NonSerialized]
        private BaseModel _selectedModel = null;

        private Dictionary<int, BaseModel> _modelLocator;
        internal Dictionary<int, BaseModel> ModelLocator
        {
            get { return _modelLocator; }
        }

        internal void DispatchCommand(string commandName, int modelID)
        {
            if (string.IsNullOrEmpty(commandName))
                return;

            _selectedModel = null;
            _selectedModel = _modelLocator[modelID];

            if (_selectedModel == null)
                throw new ArgumentException("ModelID");

            MethodInfo commandMethod = _selectedModel.GetType().GetMethod(commandName, Type.EmptyTypes);
            if (commandMethod == null)
                throw new ArgumentException("ModelCommandName");

            commandMethod.Invoke(_selectedModel, null);
        }

        internal void RefreshModelLocator(bool fullRefresh)
        {
            if (fullRefresh)
            {
                _modelLocator.Clear();
                LoadModelLocator(this);
            }
            else
            {
                foreach (KeyValuePair<int, BaseModel> addedModel in ModelAdditions)
                    _modelLocator.Add(addedModel.Key, addedModel.Value);

                foreach (int removedModelKey in ModelRemovals)
                    _modelLocator.Remove(removedModelKey);
            }
            ModelAdditions.Clear();
            ModelRemovals.Clear();
        }

        private void LoadModelLocator(BaseModel modelRoot)
        {
            _modelLocator.Add(modelRoot.ID, modelRoot);

            foreach (FieldInfo enumerableProperty in modelRoot.GetTrackableCollections())
            {
                IEnumerable items = enumerableProperty.GetValue(modelRoot) as IEnumerable;
                if (items == null)
                    continue;
                foreach (BaseModel model in items)
                    LoadModelLocator(model);
            }
        }
    }
}


